<template>
  <div class="upload-data">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <div class="search-bar">
        <el-form :model="searchForm" inline>
          <el-form-item label="条码号">
            <el-input 
              v-model="searchForm.barCode" 
              placeholder="请输入条码号" 
              clearable 
              @keyup.enter="handleSearch"
              style="width: 200px;"
            />
          </el-form-item>
          <el-form-item label="用户名">
            <el-input 
              v-model="searchForm.userName" 
              placeholder="请输入用户名" 
              clearable 
              @keyup.enter="handleSearch"
              style="width: 200px;"
            />
          </el-form-item>
          <el-form-item label="工号">
            <el-input 
              v-model="searchForm.opNum" 
              placeholder="请输入工号" 
              clearable 
              @keyup.enter="handleSearch"
              style="width: 200px;"
            />
          </el-form-item>
          <el-form-item label="操作员">
            <el-input 
              v-model="searchForm.operator" 
              placeholder="请输入操作员" 
              clearable 
              @keyup.enter="handleSearch"
              style="width: 200px;"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :loading="loading">
              🔍 搜索
            </el-button>
            <el-button @click="handleReset">
              🔄  重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 主体内容区域 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">📤 上传数据管理</span>
          <div class="header-actions">
            <div class="record-stats">
              <el-tag type="info">共 {{ total }} 条记录</el-tag>
            </div>
          </div>
        </div>
      </template>
      
      <div class="table-container">
        <el-table 
          :data="tableData" 
          style="width: 100%" 
          v-loading="loading"
          :height="tableHeight"
          class="custom-table"
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="userName" label="用户名" width="120" show-overflow-tooltip />
          <el-table-column prop="userCarId" label="身份证" width="180" show-overflow-tooltip />
          <el-table-column prop="phone" label="手机号" width="130" show-overflow-tooltip />
          <el-table-column prop="gender" label="性别" width="80" align="center" />
          <el-table-column prop="barCode" label="条码号" width="150" show-overflow-tooltip />
          <el-table-column prop="systolicPressure" label="收缩压" width="100" align="center" />
          <el-table-column prop="diastolicPressure" label="舒张压" width="100" align="center" />
          <el-table-column prop="pulse" label="脉搏" width="80" align="center" />
          <el-table-column prop="bloodConclusion" label="血压结论" width="120" align="center">
            <template #default="{ row }">
              <el-tag :type="getBloodConclusionColor(row.bloodConclusion)" size="small">
                {{ getBloodConclusionText(row.bloodConclusion) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="deviceName" label="设备名称" width="150" show-overflow-tooltip />
          <el-table-column prop="measurementTime" label="测量时间" width="180" />
          <el-table-column prop="uploadTime" label="上传时间" width="180" />
          <el-table-column prop="operator" label="操作员" width="120" show-overflow-tooltip />
          <el-table-column prop="isUpload" label="上传状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="row.isUpload === 1 ? 'success' : 'warning'" size="small">
                {{ row.isUpload === 1 ? '已上传' : '未上传' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="pageCurrent"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import { findBPUploadRecordListPage } from '../api/business.js'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const pageSize = ref(10)
const pageCurrent = ref(1)

// 搜索表单
const searchForm = reactive({
  barCode: '',
  userName: '',
  opNum: '',
  operator: ''
})

// 加载管理器
let loadingInstance = null
const showLoading = (text = '加载中...') => {
  if (loadingInstance) {
    loadingInstance.close()
  }
  loadingInstance = ElLoading.service({
    lock: true,
    text: text,
    background: 'rgba(0, 0, 0, 0.7)'
  })
}

const hideLoading = () => {
  if (loadingInstance) {
    loadingInstance.close()
    loadingInstance = null
  }
}

// 计算表格高度
const tableHeight = computed(() => {
  return 'calc(100vh - 280px)'
})

// 获取上传记录列表数据
const getData = async () => {
  loading.value = true
  
  try {
    const params = {
      pageNum: pageCurrent.value,
      pageSize: pageSize.value,
      bloodPreResults: {
        barCode: searchForm.barCode || undefined,
        userName: searchForm.userName || undefined,
        opNum: searchForm.opNum || undefined,
        operator: searchForm.operator || undefined
      }
    }
    
    const res = await findBPUploadRecordListPage(params)
    console.info('上传记录列表数据:', res)
    
    if (res && res.success === true && res.content) {
      tableData.value = res.content.list || []
      total.value = res.content.total || 0
      
      ElMessage.success(`📤 成功获取${tableData.value.length}条记录`)
    } else {
      throw new Error(res?.message || '数据格式错误')
    }
  } catch (error) {
    console.error('获取上传记录列表失败:', error)
    ElMessage.error(error.data?.message || '获取上传记录列表失败')
  } finally {
    loading.value = false
  }
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  getData()
}

const handleCurrentChange = (page) => {
  pageCurrent.value = page
  getData()
}

// 搜索处理
const handleSearch = () => {
  pageCurrent.value = 1
  getData()
}

const handleReset = () => {
  searchForm.barCode = ''
  searchForm.userName = ''
  searchForm.opNum = ''
  searchForm.operator = ''
  pageCurrent.value = 1
  getData()
}

// 血压结论处理函数
const getBloodConclusionText = (conclusion) => {
  const conclusionMap = {
    0: '正常',
    1: '血压降低',
    2: '血压升高'
  }
  return conclusionMap[conclusion] || '未知'
}

const getBloodConclusionColor = (conclusion) => {
  const colorMap = {
    0: 'success',    // 正常 - 绿色
    1: 'info',       // 血压降低 - 蓝色
    2: 'warning'     // 血压升高 - 橙色
  }
  return colorMap[conclusion] || 'info'
}

// 组件挂载时初始化
onMounted(() => {
  getData()
})
</script>

<style scoped>
.upload-data {
  background: #f5f7fa;
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.search-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.search-bar {
  display: flex;
  align-items: center;
}

.table-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
  padding-bottom: 70px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.card-title {
  font-size: 18px;
  font-weight: 700;
  color: #1e40af;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.record-stats {
  display: flex;
  align-items: center;
  gap: 8px;
}

.table-container {
  flex: 1;
  overflow: hidden;
  min-height: 0;
  display: flex;
  flex-direction: column;
}

.custom-table {
  width: 100%;
  flex: 1;
}

.pagination {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px 20px;
  display: flex;
  justify-content: flex-end;
  background: #ffffff;
  border-top: 1px solid #e4e7ed;
  z-index: 10;
}

/* 表格滚动条样式 */
:deep(.el-table) {
  height: 100% !important;
}

:deep(.el-table__body-wrapper) {
  /* 只在需要时显示滚动条 */
  overflow-y: auto !important;
  overflow-x: auto !important;
  max-height: calc(100vh - 350px) !important;
  /* 为底部分页器预留更多空间，避免遮挡 */
  padding-bottom: 10px !important;
}

/* 滚动条样式优化 */
:deep(.el-table__body-wrapper)::-webkit-scrollbar {
  width: 8px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-track {
  background: #f5f5f5;
  border-radius: 4px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 4px;
  transition: background 0.3s ease;
  min-height: 20px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb:hover {
  background: #909399;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-corner {
  background: #f5f5f5;
}

/* 表格横向铺满 */
:deep(.el-table) {
  width: 100% !important;
  min-width: 100% !important;
}

:deep(.el-table__header-wrapper),
:deep(.el-table__body-wrapper),
:deep(.el-table__footer-wrapper) {
  width: 100% !important;
}

/* 确保表格内容不会超出容器 */
:deep(.el-table__header),
:deep(.el-table__body) {
  width: 100% !important;
  table-layout: fixed;
}

/* 表格单元格内容溢出处理 */
:deep(.el-table .cell) {
  word-break: break-word;
  word-wrap: break-word;
  white-space: normal;
  line-height: 1.4;
}

/* 确保最后一行数据不被遮挡 */
:deep(.el-table__body tr:last-child td) {
  border-bottom: 1px solid #ebeef5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .upload-data {
    padding: 16px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    justify-content: space-between;
  }
}
</style>